﻿using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using OMG.Fill.Potato.Model.Ent;
using OMG.Fill.Potato.Services;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Http;
namespace OMG.Fill.Potato.Model.UI.Controllers
{
    public class PotYearProductController : ApiController
    {
        PotYearProductServices potYearProductServices = new PotYearProductServices();
        
        //[ApiActionAuthorize("获取马铃薯全年生产情况统计表分页列表对象操作")]
        //[ApiActionException]
        public Pager<List<PotYearProductEntity>> PostPageList(PotYearProductQuery query)
        {
            return potYearProductServices.GetPageList(query);
        }
        //[ApiActionAuthorize("新增马铃薯全年生产情况统计表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Post(List<PotYearProductEntity> list) {
            return potYearProductServices.AddInfo(list);
        }
        //[ApiActionAuthorize("修改马铃薯全年生产情况统计表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Put(PotYearProductEntity model)
        {
            return potYearProductServices.UpdateInfo(model);
        }
        //[ApiActionAuthorize("删除马铃薯全年生产情况统计表指定对象操作")]
        //[ApiActionException]
        public ResResult<int> Delete(string id)
        {
            return potYearProductServices.DeleteInfo(id);
        }
        //[ApiActionAuthorize("获取马铃薯全年生产情况统计表指定对象操作")]
        //[ApiActionException]
        public ResResult<List<PotYearProductEntity>> Get(string ReportId)
        {
            return potYearProductServices.GetModel(ReportId);
        }
        public ResResult<MyReportModel> Get(string AreaCode ,string FillInYear)
        {
            return potYearProductServices.GetModel(AreaCode, FillInYear);
        }
        

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="ReportId"></param>
        /// <param name="FillInYear"></param>
        /// <param name="AreaName"></param>
        public void GetExcelData(string FillInYear, string AreaCode)
        {
            AreaServices areaServices = new AreaServices();
            string AreaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";            
            string strFileName = "（一）" + FillInYear + "年"  + "-" + AreaName + "-马铃薯各品种全年生产情况统计表.xls";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));           
            curContext.Response.BinaryWrite(Method(AreaCode, FillInYear).GetBuffer());
            curContext.Response.End();
        }
        /// <summary>
        /// 获取导出数据
        /// </summary>
        /// <param name="ReportId"></param>
        /// <returns></returns>
        public MemoryStream Method(string AreaCode,string FillInYear)
        {
            FileStream file = null;
            MemoryStream ms = new MemoryStream();
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\PotDownload.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("PotYearProduct1") as HSSFSheet;//读取模板所在sheet位置
            List<PotYearProductEntity> pagelist = (List<PotYearProductEntity>)potYearProductServices.GetModel(AreaCode, FillInYear).model.list;//数据获取
            try
            {
                if (pagelist.Count != 0)
                {
                    HSSFRow row = (HSSFRow)sheet.GetRow(4);//读取模板第5行                   
                    int startRow = 4;                    
                    for (int j = 0; j < pagelist.Count; j++)
                    {
                        HSSFRow datarow = (HSSFRow)sheet.CreateRow(j+startRow);
                        datarow.CreateCell(0).SetCellValue(pagelist[j].Pvariety == null ? "" : pagelist[j].Pvariety);
                        datarow.CreateCell(1).SetCellValue(pagelist[j].YArea == null ? "" : string.Format("{0:N4}", pagelist[j].YArea));
                        datarow.CreateCell(2).SetCellValue(pagelist[j].YYield == null ? "" : string.Format("{0:N4}", pagelist[j].YYield));
                        datarow.CreateCell(3).SetCellValue(pagelist[j].YAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].YAvgMuYield));
                        datarow.CreateCell(4).SetCellValue(pagelist[j].YOutput == null ? "" : string.Format("{0:N4}", pagelist[j].YOutput));
                        datarow.CreateCell(5).SetCellValue(pagelist[j].SArea == null ? "" : string.Format("{0:N4}", pagelist[j].SArea));
                        datarow.CreateCell(6).SetCellValue(pagelist[j].SYield == null ? "" : string.Format("{0:N4}", pagelist[j].SYield));
                        datarow.CreateCell(7).SetCellValue(pagelist[j].SAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].SAvgMuYield));
                        datarow.CreateCell(8).SetCellValue(pagelist[j].SOutput == null ? "" : string.Format("{0:N4}", pagelist[j].SOutput));
                        datarow.CreateCell(9).SetCellValue(pagelist[j].AArea == null ? "" : string.Format("{0:N4}", pagelist[j].AArea));
                        datarow.CreateCell(10).SetCellValue(pagelist[j].AYield == null ? "" : string.Format("{0:N4}", pagelist[j].AYield));
                        datarow.CreateCell(11).SetCellValue(pagelist[j].AAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].AAvgMuYield));
                        datarow.CreateCell(12).SetCellValue(pagelist[j].AOutput == null ? "" : string.Format("{0:N4}", pagelist[j].AOutput));
                        datarow.CreateCell(13).SetCellValue(pagelist[j].WArea == null ? "" : string.Format("{0:N4}", pagelist[j].WArea));
                        datarow.CreateCell(14).SetCellValue(pagelist[j].WYield == null ? "" : string.Format("{0:N4}", pagelist[j].WYield));
                        datarow.CreateCell(15).SetCellValue(pagelist[j].WAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].WAvgMuYield));
                        datarow.CreateCell(16).SetCellValue(pagelist[j].WOutput == null ? "" : string.Format("{0:N4}", pagelist[j].WOutput));
                        for(int i = 0; i <= 16; i++)
                        {
                            datarow.GetCell(i).CellStyle = row.GetCell(i).CellStyle;
                        }
                    }
                    sheet.CopyTo(workbook, "Sheet1", true, true);
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;

                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.ToString().Trim());
            }
            return ms;
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="ReportId"></param>
        /// <returns></returns>
        public ResResult<int> PostImportData(string ReportId)
        {
            ResResult<int> obj = new ResResult<int>();
            ResResult<int> SingleObj = new ResResult<int>();
            HttpContext curContext = HttpContext.Current;
            HttpFileCollection files = curContext.Request.Files;

            if (curContext.Request.Files.Count != 0)
            {
                HttpPostedFile upfile = files[0];
                if (upfile != null && upfile.ContentLength > 0)
                {
                    string temppath = curContext.Server.MapPath("~/App_Data/temppath");
                    if (!Directory.Exists(temppath))//判断文件夹是否存在 
                    {
                        Directory.CreateDirectory(temppath);//不存在则创建文件夹 
                    }
                    string filetype = Path.GetExtension(upfile.FileName);
                    string filenewName = Guid.NewGuid().ToString().Replace("-", "") + filetype;
                    string strpath = Path.Combine(temppath, filenewName);
                    upfile.SaveAs(strpath);
                    List<PotYearProductEntity> list = potYearProductServices.ExcelToModel(strpath, filetype, ReportId);
                    if (list != null && list.Count > 0)
                    {
                        DictServices dicServices = new DictServices();
                        List<DictEntity> VarietyList = dicServices.GetDicByGroupCode("PotatoVariety");
                        string message = "";
                        foreach(var item in list)
                        {
                            bool tag = false;//导入的品种是否在品种表
                            foreach(var vItem in VarietyList)
                            {
                                if (item.Pvariety.Equals(vItem.DictText))
                                {
                                    tag = true;
                                }
                            }
                            if (!tag)
                            {
                                message += item.Pvariety + "   ";
                            }
                        }
                        if (message.Equals(""))
                        {
                            if(potYearProductServices.AddInfo(list).status == DefaultKey.SuccessResult)
                            {
                                obj.status = DefaultKey.SuccessResult;
                                obj.message = "数据导入成功！！";
                            }
                            else
                            {
                                obj.status = DefaultKey.ErrorResult;
                                obj.message = "数据导入失败！！";
                            }
                        }
                        else
                        {
                            message += " 不在品种表中，导入失败，请确认所导入品种！";
                            obj.status = DefaultKey.ErrorResult;
                            obj.message = message;
                        }
                    }
                    else
                    {
                        obj.status = DefaultKey.ErrorResult;
                        obj.message = "数据导入失败，请检查品种是否为空！";
                    }
                        Directory.Delete(temppath, true);
                }
            }

            return obj;
        }
        /// <summary>
        /// 获取统计列表
        /// </summary>
        /// <param name="AreaCode"></param>
        /// <param name="FillInYear"></param>
        /// <param name="Type">获取地区（0）还是品种（1）的统计列表</param>
        ///<param name="PVariety">品种</param>
        /// <returns></returns>
        public ResResult<List<YearProductStatisModel>> GetStatisListData(string AreaCode,string FillInYear,string Type,string PVariety)
        {
            return potYearProductServices.getStatisListData(AreaCode, FillInYear, Type, PVariety);
        }

        /// <summary>
        /// 统计导出
        /// </summary>
        /// <param name="AreaCode"></param>
        /// <param name="FillInYear"></param>
        public void GetStatisExcel(string AreaCode, string FillInYear, string Type,string Pvariety)
        {
            AreaServices areaServices = new AreaServices();
            string AreaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            //打开完成excel文件并下载
            HttpContext curContext = HttpContext.Current;
            // 设置编码和附件格式
            curContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            string strFileName = FillInYear + "年-" + AreaName + "-马铃薯各品种生产情况汇总表.xls";
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
            //curContext.Response.AppendHeader("Content-Disposition",
            //   "attachment;filename=" + strFileName);
            curContext.Response.BinaryWrite(loadStatis(AreaCode, FillInYear,Type, Pvariety).GetBuffer());
            curContext.Response.End();
        }

        public MemoryStream loadStatis(string AreaCode, string FillInYear, string Type,string  Pvariety)
        {
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\PotStatisLoad.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet tempsheet = templateBook.GetSheet("PotYearProduct"+Type) as HSSFSheet;//读取模板所在sheet位置
            List<YearProductStatisModel> pagelist = (List<YearProductStatisModel>)potYearProductServices.getStatisListData(AreaCode, FillInYear, Type, Pvariety).model;//数据获取

            HSSFRow row = (HSSFRow)tempsheet.GetRow(4);//读取模板第5行
            var style = row.GetCell(1).CellStyle;//读取模板第5行第2单元格样式并保存
            row.GetCell(1).CellStyle = style;//对第3行第2单元格设置原来样式

            HSSFSheet sheet = CopyToSheet(tempsheet, pagelist,Type);
            AreaServices areaServices = new AreaServices();
            string areaName = areaServices.GetByCodeModel(AreaCode).model.Name;
            sheet.CopyTo(workbook, areaName, true, true);

            //AreaServices area = new AreaServices();
            //if (AreaCode.Equals("530000000000"))
            //{
            //    var citys = areaServices.GetPrefectureList();
            //    foreach (string areacode in citys)
            //    {
            //        List<YearProductStatisModel> childlist = new List<YearProductStatisModel>();
            //        childlist = (List<YearProductStatisModel>)potYearProductServices.getStatisListData(areacode, FillInYear, Type).model;
            //        FileStream fm = new FileStream(templateName, FileMode.Open, FileAccess.Read);
            //        HSSFWorkbook Book = new HSSFWorkbook(fm);
            //        HSSFSheet temp = Book.GetSheet("PotYearProduct" + Type) as HSSFSheet;
            //        HSSFSheet sheet1 = CopyToSheet(temp, childlist, Type);
            //        string areaName1 = areaServices.GetByCodeModel(areacode).model.Name;
            //        sheet1.CopyTo(workbook, areaName1, true, true);
            //    }
            // }

                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                    return ms;
                }
        }

        public HSSFSheet CopyToSheet(HSSFSheet sheet, List<YearProductStatisModel> pagelist,string Type)
        {
            HSSFRow row = (HSSFRow)sheet.GetRow(4);
            ICellStyle style1 = sheet.Workbook.CreateCellStyle();
            int totalCells;
            if (pagelist.Count > 0)
            {
                for (int j = 0; j < pagelist.Count; j++)
                {
                    HSSFRow datarow = (HSSFRow)sheet.CreateRow(4 + j);
                    if (Type.Equals(DefaultKey.AreaType))
                    {
                        totalCells = 16;
                        datarow.CreateCell(0).SetCellValue(pagelist[j].AreaName == null ? "" : pagelist[j].AreaName);
                        datarow.CreateCell(1).SetCellValue(pagelist[j].YArea == null ? "" : string.Format("{0:N4}", pagelist[j].YArea));
                        datarow.CreateCell(2).SetCellValue(pagelist[j].YYield == null ? "" : string.Format("{0:N4}", pagelist[j].YYield));
                        datarow.CreateCell(3).SetCellValue(pagelist[j].YAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].YAvgMuYield));
                        datarow.CreateCell(4).SetCellValue(pagelist[j].YOutput == null ? "" : string.Format("{0:N4}", pagelist[j].YOutput));
                        datarow.CreateCell(5).SetCellValue(pagelist[j].SArea == null ? "" : string.Format("{0:N4}", pagelist[j].SArea));
                        datarow.CreateCell(6).SetCellValue(pagelist[j].SYield == null ? "" : string.Format("{0:N4}", pagelist[j].SYield));
                        datarow.CreateCell(7).SetCellValue(pagelist[j].SAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].SAvgMuYield));
                        datarow.CreateCell(8).SetCellValue(pagelist[j].SOutput == null ? "" : string.Format("{0:N4}", pagelist[j].SOutput));
                        datarow.CreateCell(9).SetCellValue(pagelist[j].AArea == null ? "" : string.Format("{0:N4}", pagelist[j].AArea));
                        datarow.CreateCell(10).SetCellValue(pagelist[j].AYield == null ? "" : string.Format("{0:N4}", pagelist[j].AYield));
                        datarow.CreateCell(11).SetCellValue(pagelist[j].AAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].AAvgMuYield));
                        datarow.CreateCell(12).SetCellValue(pagelist[j].AOutput == null ? "" : string.Format("{0:N4}", pagelist[j].AOutput));
                        datarow.CreateCell(13).SetCellValue(pagelist[j].WArea == null ? "" : string.Format("{0:N4}", pagelist[j].WArea));
                        datarow.CreateCell(14).SetCellValue(pagelist[j].WYield == null ? "" : string.Format("{0:N4}", pagelist[j].WYield));
                        datarow.CreateCell(15).SetCellValue(pagelist[j].WAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].WAvgMuYield));
                        datarow.CreateCell(16).SetCellValue(pagelist[j].WOutput == null ? "" : string.Format("{0:N4}", pagelist[j].WOutput));
                    }
                    else
                    {
                        totalCells = 17;
                        datarow.CreateCell(0).SetCellValue(pagelist[j].Pvariety == null ? "" : pagelist[j].Pvariety);
                        datarow.CreateCell(1).SetCellValue(pagelist[j].AreaName == null ? "" : pagelist[j].AreaName);

                        datarow.CreateCell(2).SetCellValue(pagelist[j].YArea == null ? "" : string.Format("{0:N4}", pagelist[j].YArea));
                        datarow.CreateCell(3).SetCellValue(pagelist[j].YYield == null ? "" : string.Format("{0:N4}", pagelist[j].YYield));
                        datarow.CreateCell(4).SetCellValue(pagelist[j].YAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].YAvgMuYield));
                        datarow.CreateCell(5).SetCellValue(pagelist[j].YOutput == null ? "" : string.Format("{0:N4}", pagelist[j].YOutput));
                        datarow.CreateCell(6).SetCellValue(pagelist[j].SArea == null ? "" : string.Format("{0:N4}", pagelist[j].SArea));
                        datarow.CreateCell(7).SetCellValue(pagelist[j].SYield == null ? "" : string.Format("{0:N4}", pagelist[j].SYield));
                        datarow.CreateCell(8).SetCellValue(pagelist[j].SAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].SAvgMuYield));
                        datarow.CreateCell(9).SetCellValue(pagelist[j].SOutput == null ? "" : string.Format("{0:N4}", pagelist[j].SOutput));
                        datarow.CreateCell(10).SetCellValue(pagelist[j].AArea == null ? "" : string.Format("{0:N4}", pagelist[j].AArea));
                        datarow.CreateCell(11).SetCellValue(pagelist[j].AYield == null ? "" : string.Format("{0:N4}", pagelist[j].AYield));
                        datarow.CreateCell(12).SetCellValue(pagelist[j].AAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].AAvgMuYield));
                        datarow.CreateCell(13).SetCellValue(pagelist[j].AOutput == null ? "" : string.Format("{0:N4}", pagelist[j].AOutput));
                        datarow.CreateCell(14).SetCellValue(pagelist[j].WArea == null ? "" : string.Format("{0:N4}", pagelist[j].WArea));
                        datarow.CreateCell(15).SetCellValue(pagelist[j].WYield == null ? "" : string.Format("{0:N4}", pagelist[j].WYield));
                        datarow.CreateCell(16).SetCellValue(pagelist[j].WAvgMuYield == null ? "" : string.Format("{0:N2}", pagelist[j].WAvgMuYield));
                        datarow.CreateCell(17).SetCellValue(pagelist[j].WOutput == null ? "" : string.Format("{0:N4}", pagelist[j].WOutput));
                    }
                    bool isVarrtyCount = false;
                    if (pagelist[j].AreaName != null)
                    {
                        isVarrtyCount = pagelist[j].AreaName.Equals("小计");
                    }
                    for (int i = 0; i <= totalCells; i++)
                    {
                        if (isVarrtyCount)
                        {
                           // style1.Alignment = row.GetCell(j).CellStyle.Alignment;
                            style1.FillPattern = FillPattern.SolidForeground;
                            style1.FillForegroundColor = HSSFColor.Yellow.Index;
                            datarow.GetCell(i).CellStyle = style1;
                        }
                        else
                        {
                            datarow.GetCell(i).CellStyle = row.GetCell(i).CellStyle;
                        }
                    }

                }
            }
            return sheet;
        }

    }
}